package legumes.client.ui.admin.customers;

import java.util.Date;
import java.util.List;

import legumes.client.resources.PNResources;
import legumes.client.services.callbacks.AddCustomerCallback;
import legumes.client.services.callbacks.GetCustomersCallback;
import legumes.client.services.callbacks.RemoveCustomerCallback;
import legumes.client.services.util.rpc.RPCCallSequencer;
import legumes.shared.domain.Customer;
import legumes.shared.domain.CustomerDTO;
import legumes.shared.domain.CustomerRole;

import com.google.gwt.core.client.Duration;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.types.SelectionAppearance;
import com.smartgwt.client.types.SortDirection;
import com.smartgwt.client.util.BooleanCallback;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.validator.RegExpValidator;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.EditCompleteEvent;
import com.smartgwt.client.widgets.grid.events.EditCompleteHandler;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.toolbar.ToolStrip;
import com.smartgwt.client.widgets.toolbar.ToolStripButton;

public class AdminCustomerPanel extends VLayout {
	private ListGrid lgusers;
	
	public AdminCustomerPanel() {
		super();
		setWidth100();
		setHeight100();
		
		lgusers = new ListGrid(){
			@Override  
            protected String getCellCSSText(ListGridRecord record, int rowNum, int colNum) {  
				if( record != null){
					String role=record.getAttributeAsString("role");
					if (role != null && role.equalsIgnoreCase(CustomerRole.ADMINISTRATOR.name())) {  
		                return "font-weight:bold; color:#3010C0;";  
		            } else {  
		                return super.getCellCSSText(record, rowNum, colNum);  
		            }  
				} else {
					return super.getCellCSSText(record, rowNum, colNum);
				}
	        }
	    };  
		lgusers.setWidth100();
		lgusers.setHeight100();
		
		ToolStrip toolStrip = new ToolStrip();
		toolStrip.setWidth100();
		toolStrip.setHeight(21);
		
		ToolStripButton addUserButton = new ToolStripButton();  
		addUserButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				CustomerDTO c = new CustomerDTO();
				c.setCreationDate((long)Duration.currentTimeMillis());
				c.setLastConnectionDate(-1L);
				c.setLastConnectionAddr("0.0.0.0");
				c.setRoles(CustomerRole.CUSTOMER);
				
				lgusers.startEditingNew( createListRecordUser(c) );
			}
		});
		addUserButton.setIcon(PNResources.INSTANCE.userAddIcon().getURL());  
		addUserButton.setTitle("Nouveau client...");  
        toolStrip.addButton(addUserButton);
        
        ToolStripButton delUsersButton = new ToolStripButton();
        delUsersButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				final ListGridRecord [] selectedRecords = lgusers.getSelection();
				
				BooleanCallback bc = new BooleanCallback() {
					
					@Override
					public void execute(Boolean value) {
						if( value.booleanValue() ){
							
							for(ListGridRecord r : selectedRecords){
								String userEmail = r.getAttributeAsString("email");
								final RPCCallSequencer callSequencer = new RPCCallSequencer();

								final RemoveCustomerCallback removeCustomerCallback = new RemoveCustomerCallback(
										userEmail);
								callSequencer.addCall(removeCustomerCallback);
								callSequencer.callSequence();
							}
							lgusers.removeSelectedData();
						}
					}
				};
				if(selectedRecords == null || selectedRecords.length <= 0){
					SC.say("Vous devez s&eactue;lectionner des utilisateurs dans la grille pour les supprimer.");
				} else if(selectedRecords.length==1) {
					String userName = selectedRecords[0].getAttributeAsString("name");
					SC.confirm("Suppression d'un utilisateur", 
							"Etes vous sur de vouloir supprimer l'utilisateur " + userName + "  ?", 
							bc);
				} else {
					SC.confirm("Suppression d'utilisateurs", 
							"Etes vous sur de vouloir supprimer les " + selectedRecords.length +" utilisateurs s&eacute;lectionn&eactues ?", 
							bc);
				}
			}
		});
        delUsersButton.setIcon(PNResources.INSTANCE.userDeleteIcon().getURL());  
        delUsersButton.setTitle("Supprimer les clients sélectionnés");  
        toolStrip.addButton(delUsersButton);  
        
        
		ListGridField lgfEmail = new ListGridField("email", "Email", 150);
		lgfEmail.setCanEdit(true);
		RegExpValidator emailRegExpValidator = new RegExpValidator();  
		emailRegExpValidator.setExpression("^([a-zA-Z0-9_.\\-+])+@(([a-zA-Z0-9\\-])+\\.)+[a-zA-Z0-9]{2,4}$");  
        lgfEmail.setValidators(emailRegExpValidator);
		
        ListGridField lgfName = new ListGridField("name", "Nom", 100);
        lgfName.setCanEdit(true);
		ListGridField lgfRole = new ListGridField("role", "Profil", 100);
		lgfRole.setCanEdit(true);
		lgfRole.setValueMap(CustomerRole.CUSTOMER.name(), CustomerRole.ADMINISTRATOR.name());
		
		ListGridField lgfCreationDate = new ListGridField("creationDate", "Cr&eacute;ation", 100);
		lgfCreationDate.setCanEdit(false);
		lgfCreationDate.setType(ListGridFieldType.DATE);
		
		ListGridField lgfLastConnexionIpAdress = new ListGridField("lastConnexionIpAddr", "IP derni&egrave;re connexion", 100);
		lgfLastConnexionIpAdress.setCanEdit(false);
		
		ListGridField lgfLastConnexionDate = new ListGridField("lastConnexionDate", "Derni&egrave;re connexion");
		lgfLastConnexionDate.setCanEdit(false);
		lgfLastConnexionDate.setType(ListGridFieldType.DATE);
		
		lgusers.setFields(lgfEmail, lgfName, lgfRole, lgfCreationDate, 
				lgfLastConnexionIpAdress, lgfLastConnexionDate);
		
		lgusers.setSortField(0);  
		lgusers.setSortDirection(SortDirection.ASCENDING);  
		lgusers.setSelectionAppearance(SelectionAppearance.CHECKBOX); 
		lgusers.addEditCompleteHandler(new EditCompleteHandler() {
			
			@Override
			public void onEditComplete(EditCompleteEvent event) {
				ListGridRecord lgr = lgusers.getRecord(event.getRowNum());
				
				Customer customerToAdd = new Customer();
				customerToAdd.setEmail(lgr.getAttributeAsString("email"));
				customerToAdd.setName(lgr.getAttributeAsString("name"));
				customerToAdd.setPassword(lgr.getAttributeAsString("email"));
				customerToAdd.setRoles(lgr.getAttributeAsString("role"));
				customerToAdd.setCreationDate(lgr.getAttributeAsDate("creationDate").getTime() );
				
				RPCCallSequencer callSequencer = new RPCCallSequencer(
						"Enregistrement en cours...");
				final AddCustomerCallback addCustomerCallback = new AddCustomerCallback(
						customerToAdd);
				callSequencer.addCall(addCustomerCallback);

				callSequencer.addRunnable(new Runnable() {
					public void run() {
						if (addCustomerCallback.getAddedCustomer() == null) {
							return;
						}
					}
				});

				callSequencer.callSequence();
			}
		});
        
		setMembers(toolStrip, lgusers);
		initData();
	}
	
	public void initData(){
		RPCCallSequencer callSequencer = new RPCCallSequencer(
		"Chargement en cours...");

		final GetCustomersCallback getCustomersCallback = new GetCustomersCallback();
		
		callSequencer.addCall(getCustomersCallback);
		callSequencer.addRunnable(new Runnable() {
			public void run() {
				displayCustomers(getCustomersCallback.getCustomers());
			}
		});
		
		callSequencer.callSequence();
	}
	
	protected void displayCustomers(List<CustomerDTO> customers_) {
		ListGridRecord[] records = new ListGridRecord[customers_.size()];
		int i = 0;
		for (CustomerDTO c : customers_) {
			records[i] = createListRecordUser(c);
			i++;
		}
		
		lgusers.setRecords(records);
	}
	
	private ListGridRecord createListRecordUser(CustomerDTO c_){
		ListGridRecord lgr = new ListGridRecord();
		lgr.setAttribute("email", c_.getEmail());
		lgr.setAttribute("name", c_.getName() );
		lgr.setAttribute("role", c_.getRoles() );
		
		lgr.setAttribute("creationDate", new Date(c_.getCreationDate()));
		lgr.setAttribute("lastConnexionIpAddr", c_.getLastConnectionAddr());
		lgr.setAttribute("lastConnexionDate", new Date(c_.getCreationDate()));
		return lgr;
	}

	public void refreshData() {
		initData();
	}
}
